package com.zzr.zzrbackend.service.Impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zzr.zzrbackend.pojo.dto.CommonResult;
import com.zzr.zzrbackend.pojo.dto.result.FileUploadListResult;
import com.zzr.zzrbackend.pojo.dto.result.FileUploadResult;
import com.zzr.zzrbackend.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {
    public CommonResult<FileUploadListResult> upload(List<MultipartFile> file, Integer fileType) {
        //初始化返回
        FileUploadListResult fileUploadListResult = new FileUploadListResult();
        List<FileUploadResult> list = new ArrayList<>();

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //生成上传凭证，然后准备上传
        String accessKey = "r1-IA5mDjhyAmyybuosKv5L8QoCMteHHD0TNyngJ";
        String secretKey = "ctI0ljVA9eKeDqrI3rbOUpTfxsoVrX8u9D9GmILz";
        String bucket = "yuleng-hbws";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String catalogue = "";
        if (fileType == 1) {
            catalogue = "image/";
        } else if (fileType == 2) {
            catalogue = "audio_ai/init/";
        }

        for (MultipartFile fileSingle : file) {
            long startTime = System.currentTimeMillis();
            //初始化
            FileUploadResult fileUploadResult = new FileUploadResult();
            String key = fileSingle.getOriginalFilename();
            File fileUpload = new File(key);
            OutputStream out = null;
            try {
                //获取文件流，以文件流的方式输出到新文件
                //InputStream in = multipartFile.getInputStream();
                out = new FileOutputStream(fileUpload);
                byte[] ss = fileSingle.getBytes();
                for (int i = 0; i < ss.length; i++) {
                    out.write(ss[i]);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            //存文件大小
            double fileSizeMB = (double) fileUpload.length() / 1024 / 1024;

            fileUploadResult.setFileSize(String.format("%.3fMB", fileSizeMB));

            //进行七牛云储存
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(fileUpload, catalogue + key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
            // 操作完上的文件 需要删除在根目录下生成的文件
            File f = new File(fileUpload.toURI());
            if (f.delete()) {
                log.info(key + "删除成功");
            } else {
                log.info(key + "删除失败");
            }
            long endTime = System.currentTimeMillis();
            String fileUrl = "http://hbws.file.yuleng.top/" + catalogue + key;
            fileUploadResult.setFileUrl(fileUrl);
            fileUploadResult.setFileName(key);
            fileUploadResult.setUploadTime(endTime - startTime + "ms");
            list.add(fileUploadResult);
        }
        fileUploadListResult.setFiles(list);
        return CommonResult.success(fileUploadListResult);
    }
}
